package com.zy.explore.design.patterns.responsibilitychain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class ResponsibilityChainUseService {

    /**
     * 自动注入各个责任链的对象
     */
    @Autowired
    private List<AbstractHandler> abstractHandlerList;

    private AbstractHandler abstractHandler;

    /**
     * spring注入后自动执行初始化责任链（将责任链中的所有对象连起来）
     */
    @PostConstruct
    public void initializeChainFilter() {
        for (int i = 0; i < abstractHandlerList.size(); i++) {
            if (i == 0) {
                abstractHandler = abstractHandlerList.get(0);
            } else {
                AbstractHandler currentHandler = abstractHandlerList.get(i - 1);
                AbstractHandler nextHandler = abstractHandlerList.get(i);
                currentHandler.setNextHandler(nextHandler);
            }
        }
    }

    /**
     * 外部直接调用此方法来执行责任链中真正要执行的方法
     *
     * @param request  请求
     * @param response 响应
     * @return {@link HttpServletResponse}
     */
    public HttpServletResponse exec(HttpServletRequest request, HttpServletResponse response) {
        abstractHandler.filter(request, response);
        return response;
    }

    /**
     * 获取责任链中的处理器
     *
     * @return {@link AbstractHandler}
     */
    public AbstractHandler getAbstractHandler() {
        return abstractHandler;
    }

    /**
     * 设置责任链中的处理器
     *
     * @param abstractHandler 抽象的处理程序
     */
    public void setAbstractHandler(AbstractHandler abstractHandler) {
        this.abstractHandler = abstractHandler;
    }
}
